/**
 * 文件：activity_photograph.java
 * 包名：com.ronri.ams.sample;   --- 正式发布时需要修正
 * 说明：拍照系统
 * 作者：MS During
 * 日期：2017/5/12
 * 历史：
 */
package com.ronri.ams.sample;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.GridView;

import com.alibaba.fastjson.JSON;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.choosephotos.PhotoGridAdapter;
import com.ronri.choosephotos.PhotoItem;
import com.ronri.common.BitmapManager;
import com.ronri.common.FileManager;
import com.ronri.mapapi.location.service.LocationManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



//import com.ronri.PhotoGraph.activity.CameraActivity;

public class activity_photograph extends abstract_activity implements View.OnClickListener {

    // 照片保存路径及文件名
    public String mFilePath = "";

    // 照片保存文件名称
    public String mFileName = "";

    // 找显示视图
    public GridView mGridView = null;

    // 照片信息
    public List<PhotoItem> mItems = new ArrayList<PhotoItem>();

    public double mLat, mLng;

    public String mAddress;

    private boolean onlyOnePhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.control_photograph);
        Log.i("aaa", "activity_photograph");
        // 读取参数
        Bundle bundle = getIntent().getExtras();

        int editLayout = bundle.getInt("edit_layout", R.layout.control_edit_box);
        String szTitle = bundle.getString("title");
        String szvTitle = bundle.getString("vtitle");
        String szPhotoJson = bundle.getString("data");
        onlyOnePhoto = bundle.getBoolean("onlyOnePhoto", false);

        // 显示标题与右边功能
        setTitle(szTitle, szvTitle);

        // 初始化内容
        init();

        // 转换数据
        mItems = JSON.parseArray(szPhotoJson, PhotoItem.class);

        // 防止无数据错误
        if (mItems == null)
            mItems = new ArrayList<PhotoItem>();

        PhotoItem oper = null;

        for (PhotoItem item : mItems) {
            if (item.isOperator) {
                oper = item;
                break;
            }
        }

        // 添加操作视图
        if (oper == null)
            mItems.add(new PhotoItem(true));

        mGridView = (GridView) findViewById(R.id.gvPhotoLayout);

        PhotoGridAdapter photoGridAdapter = new PhotoGridAdapter(this, mItems, getLayoutInflater(), this);
        mGridView.setAdapter(photoGridAdapter);

        LocationManager.getLocationInfo(new LocationManager.OnLocationEvent() {

            @Override
            public void OnLocationResult(double lat, double lng, String szAddress) {
                mLat = lat;
                mLng = lng;
                mAddress = szAddress;
            }
        });
    }

    @Override
    public boolean CancelReturn() {
        setResult(RESULT_CANCELED);
        return super.CancelReturn();
    }

    @Override
    public boolean SureReturn() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();

        if (mItems.size() > 0)
            mItems.remove(mItems.size() - 1);

        // 结果
        String resultString = JSON.toJSONString(mItems);

        bundle.putString("returnValue", resultString);
        intent.putExtras(bundle);

        this.setResult(RESULT_OK, intent);

        mItems.clear();

        return super.SureReturn();
    }

    /***
     * 启动摄像头
     */
    public void StartCamera() {
        //        // 创建摄像头控制句柄
        Intent intent = new Intent(this, activity_control_photograph.class);
        //
        //        // 创建目录，避免出现错误
        FileManager.DirExists(InitApplication.PhotoSavePath + "original/");
        //
        //        // 生成文件名称
        mFileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        //
        //        // 创建文件访问控制
        File file = new File(InitApplication.PhotoSavePath + "original/", mFileName);
        //
        //        // 解析文件名称
        Uri imageUri = Uri.fromFile(file);
        //
        //        // 获取文件名称
        mFilePath = imageUri.getPath();
        //
        Bundle bundle = new Bundle();
        bundle.putString("photoFilePath", mFilePath);
        intent.putExtras(bundle);
        //        // 控制参数
        // intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //
        //        // 调用系统的摄像机拍摄照片
        //        startActivityForResult(intent, SystemApplication.Activity_RESULT_GET_PHOTO);
        //
        //        Intent intent = new Intent(this, CameraActivity.class);
        //
        //        startActivity(intent);
        //        Intent intent = new Intent(this, activity_control_photograph.class);
        startActivityForResult(intent, InitApplication.Activity_RESULT_GET_PHOTO);
    }

    /***
     * 接收来自照片系统的数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == InitApplication.Activity_RESULT_GET_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                // 获取存储路径
                // String szPath = getResources().getString(R.string.Photo_Result_Save_Path);
                Bitmap bitmap = BitmapManager.getimage(mFilePath, 50);

                // 保存照片信息，进行压缩
                FileManager.saveCompressBitmap(
                        InitApplication.PhotoSavePath + "after/", mFileName,
                        bitmap,
                        100);

                if (!bitmap.isRecycled()) {
                    /// 释放内存
                    bitmap.recycle();
                    System.gc();
                }

                PhotoItem photoItem = new PhotoItem(false);
                photoItem.PhotoPath = InitApplication.PhotoSavePath + "after/" + mFileName;
                photoItem.setLatitude(mLat);
                photoItem.setLongitude(mLng);
                photoItem.setAddress(mAddress);
                photoItem.setPhotoDate(new Date());

                //                if( gSampleInfo.getSample_attach() == null)
                //                    gSampleInfo.setSample_attach(new ArrayList<sample_info.SampleAttachBean>());

                //                sample_info.SampleAttachBean attachBean = new sample_info.SampleAttachBean();
                //                attachBean.setCreate_user(SystemApplication.LoginInfo.getData().getUser_id());
                //                attachBean.setAttach_name(mFileName);
                //                attachBean.setLatitude(String.valueOf(mLat));
                //                attachBean.setLongitude(String.valueOf(mLng));
                //                attachBean.setLocation(mAddress);
                //                gSampleInfo.getSample_attach().add(attachBean);
                //                gSampleInfo.getSample_breed().get(1).getBreed_attach().add(attachBean);



                //判断是否为添加样品中的照片
                if (onlyOnePhoto && mItems.size() > 1) {
                    mItems.set(0,photoItem);
                }else{
                    mItems.add(0, photoItem);
                }

                // 刷新记录
                ((PhotoGridAdapter) mGridView.getAdapter()).setPhotoGridData(mItems);
            }
        }

        if (requestCode == SystemEnvironmental.PhotoGraph_Detail_Result) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    String szJson = bundle.getString("returnValue", "");
                    mItems = JSON.parseArray(szJson, PhotoItem.class);
                    // 刷新记录
                    ((PhotoGridAdapter) mGridView.getAdapter()).setPhotoGridData(mItems);
                }
            }
        }
    }

    /***
     * GridView点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        if (view.getTag() instanceof String) {
            if (view.getTag().toString() == "addphoto") {
                StartCamera();
            }
        } else {
            if (view.getTag() instanceof PhotoItem) {

                // 显示大图片
                PhotoItem photoItem = (PhotoItem) view.getTag();

                int nIndex = 0;
                for (PhotoItem iTem : mItems) {
                    if (photoItem == iTem) {
                        break;
                    }
                    nIndex++;
                }

                Intent intent = new Intent(getBaseContext(), activity_photo_detail.class);

                Bundle bundle = new Bundle();

                String aaa = JSON.toJSONString(mItems);

                bundle.putString("title", "照片管理");
                bundle.putString("vtitle", "");
                bundle.putString("data", aaa);
                bundle.putInt("index", nIndex);

                intent.putExtras(bundle);
                startActivityForResult(intent, SystemEnvironmental.PhotoGraph_Detail_Result);
            }
        }
    }
}
